package listdemo;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

class Person implements Comparable<Person>{

    private String name;
    private String gender;
    private int age;

    public Person(String name, String gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int compareTo(Person person) {   //重写Comparable接口的compareTo方法，
        return this.age - person.getAge(); // 根据年龄升序排列，降序修改相减顺序即可
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                '}';
    }
}
public class ListSortByComparableDemo {

    public static void main(String[] args) {
        List list = new LinkedList();
        Person s1 = new Person("张三","男",20);
        Person s2 = new Person("李四","女",18);
        Person s3 = new Person("王五","男",21);
        Person s4 = new Person("赵六","女",22);

        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);

        Collections.sort(list);

        for(Object obj: list){
            System.out.println(obj);
        }
    }

}
